﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

using SManaApi.Helpers;
using SManaApi.Services;

using SManaModel;
using SManaModel.dtos;
using SManaModel.entities;
using SManaModel.models;
using SManaModel.utils;

using System;

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SManaApi.Controllers
{
    /// <summary>
    /// 登录模块
    /// </summary>
    [Route("api")]
    [ApiController]
    public class LoginController : MasterController<LoginController>
    {
        private readonly TokenConfig _token;
        private readonly JwtService _jwtService;
        private readonly LoginService _loginService;

        public LoginController(ILogger<LoginController> logger,
                               MyDbContext context,
                               TokenConfig token,
                               JwtService jwtService,
                               LoginService loginService) : base(logger, context)
        {
            _token = token;
            _jwtService = jwtService;
            _loginService = loginService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("login")]
        public ApiResult Login([FromBody] LoginDto? dto)
        {
            if (dto is null)
            {
                return ApiResult.Fail(msg: "参数错误");
            }

            if (!UserHelper.IsInUserType(dto.type, out var userType))
            {
                return ApiResult.Fail(msg: "参数错误");
            }

            var person = _loginService.Login(dto.type, dto.name, dto.pwd);
            if (person == null)
            {
                return ApiResult.Fail(msg: "用户名或密码错误");
            }

            // 生成jwt
            var claims = new[]
           {
                new Claim("id", (((dynamic)person).Id).ToString()),
                new Claim("type", dto.type.ToUpper()),
            };
            var token = _jwtService.SetToken(HttpContext, claims);

            var userInfoDto = person.ConvertTo<UserInfoDto>();
            userInfoDto.type = dto.type.ToUpper();
            return ApiResult.Ok(data: new
            {
                user_info = userInfoDto,
                token = token
            });
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("logout")]
        public ApiResult Logout()
        {
            // TODO 用户jwt存在就删除
            var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_token.Secret));
            return ApiResult.Ok();
        }
    }
}
